package com.cooper.resource.download;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;

import android.util.Log;

import com.cooper.resource.download.DownloadResource.DownloadItem;
import com.cooper.scraper.HttpDownload;
import com.cooper.scraper.R;

public class FileDownThread extends DownThread {

	public FileDownThread(HttpDownload httpDownload,
			DownloadStatus downloadStatus, DownloadItem item) {
		super(httpDownload, downloadStatus, item);
	}

	@Override
	protected void runDownload() {
		if (Thread.currentThread().isInterrupted()) {
			return;
		}
		try {
			download();
			if (downLength >= item.getFileSize()) {
				item.setFinish(true);
				downloadStatus.saveDownInfo();
				return;
			}
		} catch (Exception e) {
			Log.e("BlockDownThread", e.getMessage(), e);
		}
		if (!downloadStatus.downFail(R.string.download_fail,DownloadStatus.FAIL_FOR_CANT_CONTINUE)) {
			try {
				sleep(10000);
				runDownload();
			} catch (InterruptedException e1) {
				Log.d("BlockDownThread", "Thread is Trim", e1);
			}
		}

	}

	private void download() throws IOException {
		downLength = 0;
		item.setFinish(false);
		item.setDownLength(0);
		HttpURLConnection conn = httpDownload.createDefaultConn(item.getUrl());
		try {
			InputStream inStream = new BufferedInputStream(
					conn.getInputStream(), STREAM_BUFFER_SIZE);
			try {
				File saveFile = item.getTargetFilePath();
				if (saveFile.exists()) {
					saveFile.delete();
				}

				byte[] buffer = new byte[1024];
				FileOutputStream fos = new FileOutputStream(saveFile);

				try {
					int ch = -1;
					while (!Thread.currentThread().isInterrupted()
							&& (ch = inStream.read(buffer, 0, 1024)) != -1) {
						fos.write(buffer, 0, ch);
						if (!Thread.currentThread().isInterrupted()) {
							downLength += ch;
							downloadStatus.updateDownLen();
							item.setDownLength(downLength);
						} else {
							if (saveFile.exists()) {
								saveFile.delete();
							}
							return;
						}
					}
					if (!Thread.currentThread().isInterrupted())
						fos.flush();
				} finally {
					fos.close();
				}

			} finally {
				inStream.close();
			}
		} finally {
			conn.disconnect();
		}

	}

}
